package com.songlanyun.common.supplychainapi.common;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.jxhh.ApiClient;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.custom.ClassConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

@Component
@Slf4j
public class ApiRequestCommon {

    @Resource
    private ApiClient apiClient;

    public <T> T exec(String url, ApiClient.RequestMethod method, Map<String, Object> params, Class<T> responseClass, String errorMsg) {
        TreeMap<String, Object> paramsMap = new TreeMap<String, Object>();
        if (MapUtil.isNotEmpty(params)) {
            paramsMap = new TreeMap<>(params);
        }

        try {
            String result = apiClient.exec(method, url, paramsMap);
            ResultCommon resultCommon = ClassConvertUtils.stringToClassSnake(result, new TypeReference<ResultCommon>() {
            });

            if (ObjectUtil.isNull(resultCommon) || resultCommon.getCode() != 1) {
                String msg = StringUtils.isNotEmpty(resultCommon.getMsg())?resultCommon.getMsg():resultCommon.getMessage();
                throw new RRException(errorMsg + ":" + msg);
            }
            if (ObjectUtil.isNull(resultCommon.getData()) || ObjectUtil.isNull(responseClass)) {
                return null;
            }
            return JSON.parseObject(JSON.toJSONString(resultCommon.getData()), responseClass);
//            return ClassConvertUtils.transformObject(resultCommon.getData(), responseClass);
        } catch (IOException e) {
            log.error(errorMsg + "[接口报错]:" + e.getMessage());
            throw new RRException(errorMsg + ":异常");
        }

    }

}
